﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleServer.Net
{
    public class ByteArray
    {
        public byte[] Bytes;//缓冲区
        public const int DEFAULT_SIZE = 1024;//默认大小
        public int m_InitSize;//起始大小
        public int Capacity;//容量
        public int ReadIdx;//读取位置
        public int WriteIdx;//写入位置
        public int Reamin { get { return Capacity - WriteIdx; } }//剩余空间
        public int Length { get { return WriteIdx - ReadIdx; } }//消息长度

        public ByteArray()
        {
            Bytes = new byte[DEFAULT_SIZE];
            Capacity = DEFAULT_SIZE;
            m_InitSize = DEFAULT_SIZE;
            ReadIdx = 0;
            WriteIdx = 0;
        }
        //检测并移动数据
        //一条消息构成：包头（包的名字长度和包的内容长度）+包的名字+包的内容
        public void CheckAndMoveBytes()
        {
            if (Length < 8)
            {
                if (ReadIdx < 0)
                {
                    return;
                }
                //进行数据移动
                Array.Copy(Bytes, ReadIdx, Bytes, 0, Length);
                WriteIdx = Length;
                ReadIdx = 0;
            }
        }
        //数据缓冲区扩容
        public void ReSize(int size)
        {
            if (ReadIdx < 0)
            {
                return;
            }
            if (size < Length)
            {
                return;
            }
            if (size < m_InitSize)
            {
                return;
            }
            int n = 1024;
            while (n < size)
            {
                n *= 2;
            }
            Capacity = n;
            byte[] newBytes = new byte[Capacity];
            Array.Copy(Bytes, ReadIdx, newBytes, 0, Length);
            Bytes = newBytes;
            WriteIdx = Length;
            ReadIdx = 0;
        }
    }
}
